package com.bestwond.test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class OpenBoxDemo {

    public static String getPost(String url, Map<String, String> heads,
                                 Map<String, String> params) throws IOException {

        URL u;
        HttpURLConnection connection = null;
        OutputStream out;
        try {
            u = new URL(url);
            connection = (HttpURLConnection) u.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            if (heads != null) {
                for (Map.Entry<String, String> stringStringEntry : heads.entrySet()) {
                    connection.setRequestProperty(stringStringEntry.getKey(),
                            stringStringEntry.getValue());
                }
            }

            out = connection.getOutputStream();
            if (params != null && !params.isEmpty()) {
                out.write(toJSONString(params).getBytes());
            }
            out.flush();
            out.close();

            InputStream is = connection.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int i;
            while ((i = is.read()) != -1) {
                baos.write(i);
            }
            return baos.toString();

        } catch (Exception e) {
            throw e;
        }
    }

    public static String toJSONString(Map<String, String> map) {
        Iterator<Map.Entry<String, String>> i = map.entrySet().iterator();
        if (!i.hasNext()) {
            return "{}";
        }
        StringBuilder sb = new StringBuilder();
        sb.append('{');
        for (; ; ) {

            Map.Entry<String, String> e = i.next();
            String key = e.getKey();
            String value = e.getValue();
            sb.append("\"");
            sb.append(key);
            sb.append("\"");
            sb.append(':');
            sb.append("\"");
            sb.append(value);
            sb.append("\"");
            if (!i.hasNext()) {
                return sb.append('}').toString();
            }
            sb.append(',').append(' ');
        }
    }

    public static String create_sign(String params, String app_secret) {
        params = params + app_secret;
        byte[] bytes = params.getBytes(StandardCharsets.UTF_8);
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance("SHA-512");
            messageDigest.update(bytes);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA sign error");
        }
        byte[] digest = messageDigest.digest();
        return byteArrayToHexString(digest);
    }

    private static String byteArrayToHexString(byte[] bytes) {
        StringBuilder builder = new StringBuilder();
        for (byte b : bytes) {
            String temp = Integer.toHexString(b & 0xFF);
            if (temp.length() == 1) {
                builder.append("0");
            }
            builder.append(temp);
        }
        return builder.toString();
    }


    public static void main(String[] args) throws IOException {
        Map<String,String> map =new TreeMap<>((k1, k2)->{
            return k1.compareTo(k2);
        });

        map.put("app_id", "bw_de27*******11e");
        map.put("timestamps", String.valueOf(System.currentTimeMillis()/1000));
        map.put("device_number", "200****001");
        map.put("lock_address", "0101");
        map.put("use_type", "S");

        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            sb.append(entry.getKey() + "=" + entry.getValue() + "&");
        }
        String params = sb.toString();
        if (sb.length() > 0) {
            params = sb.substring(0, sb.length()-1);
        }
        String sign = create_sign(params, "de27690e21f911e**********e198b20");
        map.put("sign", sign);
        Map<String,String> headers = new HashMap<>();

        String result = getPost("https://api.bestwond.com/api/iot/open/box/?sign="+sign, headers, map);
        System.out.println(result);
    }
}
